package org.swingplus.core.scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swingplus.core.annotation.bean.Bean;
import org.swingplus.core.annotation.bean.Bind;
import org.swingplus.core.annotation.bean.Binds;
import org.swingplus.core.annotation.bean.ReturnType;
import org.swingplus.core.context.ApplicationContext;
import org.swingplus.core.exception.BeanCreateException;
import org.swingplus.core.exception.BeanNoFindException;
import org.swingplus.core.utils.StringUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BindScan {

	private String ssdsd;
	private int w;

	public BindScan(String ssdsd,int w){
		this.ssdsd=ssdsd;
		this.w=w;
	}


	private static final Logger logger = LoggerFactory.getLogger(BindScan.class);

	/**
	 * 方法上声明用@Bean
	 * 
	 * @param clazz
	 */
	public static void scan(Class<?> clazz) {

		List<Object> instance = new ArrayList<>();
		for (Object object : instance) {
			scan(instance);
		}
		return;

	}
	public static void scan(Object obj) {
		Field[] fields = obj.getClass().getFields();
		for(Field field:fields){
			Object fieldObj=null;
			field.setAccessible(true);

			try{
				fieldObj = field.get(obj);
			}catch (IllegalAccessException e){
				e.printStackTrace();
			}
			if(null==fieldObj){
				throw new BeanCreateException("");
			}



			Binds bindS=field.getAnnotation(Binds.class);
			if(null!=bindS){
				Bind[] binds=bindS.value();
				for(Bind bind:binds){
					doBind(fieldObj,bind);
				}
			}else{
				Bind bind=field.getAnnotation(Bind.class);
				if(null!=bind){
					doBind(fieldObj,bind);
				}
			}
		}




		return;

	}

	private static void doBind(Object obj,Bind bind) {
		String type=bind.type();
		String target=bind.target();
		String association=bind.association();

		if(type.equals("LISTEN")){

             Object targetObj=ApplicationContext.getBean(target);
             if(null==targetObj){
             	throw new BeanNoFindException("");
			 }




			addListener(obj,targetObj,association);

		}

//		addListener(field.get(obj),target,association);
//
//		StringUtil.lowerFirst(instanceName); // 大写转小写方法

	}

	private static void addListener(Object obj,Object target, String association) {

		try {
			Method method=obj.getClass().getDeclaredMethod(association);

			if (method.getParameterTypes().length == 0) {
				method.invoke(obj);
			} else {
				if(target instanceof Constructor){
					try {
						target=((Constructor)target).newInstance(obj);
					} catch (InstantiationException e) {
						e.printStackTrace();
					}
				}



				method.invoke(obj, target);
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}


	}
}
